<template>
  <div>
    <el-dialog
      :title="diaInfo.isAdd ? '添加商品管理' : '编辑商品管理'"
      :visible.sync="diaInfo.isShow"
      center
      :before-close="cancel"
      @opened="createEdit"
    >
      <el-form :model="goodsForm" ref="goodsRef" :rules="rules"
        ><el-form-item label="一级分类" :label-width="formLabelWidth">
          <el-select
            v-model="goodsForm.first_cateid"
            @change="changeCate(false)"
            placeholder="请选择"
          >
            <el-option
              v-for="item in catelist"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类" :label-width="formLabelWidth">
          <el-select v-model="goodsForm.second_cateid" placeholder="请选择">
            <el-option
              v-for="item in cateArr"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsname" :label-width="formLabelWidth">
          <el-input autocomplete="off" v-model="goodsForm.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price" :label-width="formLabelWidth">
          <el-input autocomplete="off" v-model="goodsForm.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" prop="market_price" :label-width="formLabelWidth">
          <el-input autocomplete="off" v-model="goodsForm.market_price"></el-input>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth">
          <!-- 
            el-upload
            on-preview	点击文件列表中已上传的文件时的钩子	
            action	必选参数，上传的地址
            list-type	文件列表的类型
            auto-upload	是否在选取文件后立即进行上传
            on-change	文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
            file-list	上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]	array
            limit	最大允许上传个数
            注意： 
            图片上传一般有两种方式
            1、直接把图片上传到服务器 以流文件的形式
            2、通过一个接口（上传接口）
            :on-remove="handleRemove"
           -->
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="onPreview"
            :auto-upload="false"
            :on-change="onChange"
            :file-list="fileList"
            :limit="1"
            :on-exceed="onExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品规格" prop="specsid" :label-width="formLabelWidth">
          <el-select
            v-model="goodsForm.specsid"
            @change="changeSpecs"
            placeholder="请选择"
          >
            <el-option
              v-for="item in specslist"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" prop="specsattr" :label-width="formLabelWidth">
          <!-- multiple	是否多选 -->
          <el-select v-model="goodsForm.specsattr" multiple placeholder="请选择">
            <el-option
              v-for="item in specsArr"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="goodsForm.isnew" :label="1">是</el-radio>
          <el-radio v-model="goodsForm.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="goodsForm.ishot" :label="1">是</el-radio>
          <el-radio v-model="goodsForm.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-tooltip :content="'Switch value: ' + value" placement="top">
            <el-switch
              v-model="goodsForm.status"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="2"
            >
            </el-switch>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="edit"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { goodsAdd, goodsInfo, goodsEdit } from "../../request/api.js";
import E from "wangeditor";
export default {
  props: ["diaInfo"],
  data() {
    return {
      goodsForm: {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, // 是否新品     1-是 2-否
        ishot: 1, // 是否热卖推荐 1-是 2-否
        status: 1, //状态1正常2禁用
      },
      formLabelWidth: "120px",
      dialogImageUrl: "",
      dialogVisible: false,
      radio: "1",
      value: "1",
      cateArr: [], //二级分类
      specsArr: [], //规格属性的二级分类
      fileList: [],
      edit: null, //编辑器
      //规则验证
      rules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        market_price: [{ required: true, message: "请输入市场价格", trigger: "blur" }],
        first_cateid: [{ required: true, message: "请选择一级分类", trigger: "change" }],
        second_cateid: [{ required: true, message: "请选择二级分类", trigger: "blur" }],
        specsid: [{ required: true, message: "请选择商品规格", trigger: "change" }],
        specsattr: [{ required: true, message: "请选择规格属性", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 辅助函数
    ...mapActions({
      getCate: "cate/getCateListActions",
      getspecs: "specs/getSpecsListActions",
      getGoodsListActions: "goods/getGoodsListActions",
      getCountActions: "goods/getCountActions",
    }),
    // 封装取消方法
    cancel() {
      this.$emit("cancel", false);
      this.reset();
    },
    // 封装一个一级分类切换事件，用于获取当前选中状态
    changeCate(n) {
      //思路：知道当前用户选中的id值，拿id去数组中进行查找，找到所在下标，自然获得当前数组下标下的children
      let index = this.catelist.findIndex(
        (item) => item.id == this.goodsForm.first_cateid
      );
      //   console.log(index);
      //   console.log(this.catelist);
      this.cateArr = this.catelist[index].children;
      // console.log(this.cateArr);
      //   console.log(this.cateArr.second_cateid);
      // 清空二级分类的双向数据绑定值
      if (!n) {
        this.goodsForm.second_cateid = "";
      }
    },
    changeSpecs(n) {
      let index = this.specslist.findIndex((item) => item.id == this.goodsForm.specsid);
      //   console.log(index);
      this.specsArr = this.specslist[index].attrs;
      //   console.log(this.specsArr);
      if (!n) {
        this.goodsForm.specsattr = "";
      }
    },
    // 文件发生变化触发的函数
    onChange(file, fileList) {
      //   console.log(file);
      this.goodsForm.img = file.raw;
    },
    // 文件限制方法
    onExceed(files, fileList) {
      // console.log(files.length,fileList.length);
      this.$message.warning(
        `只能选择一个文件，本次选择了${files.length}个文件，一共选择了${files.length}`
      );
    },
    //移除触发的钩子函数
    // handleRemove(file, fileList) {
    //   console.log(file, "移除", fileList);
    // },
    // 预约回调函数
    onPreview(file) {
      console.log(file, "文件");
    },
    // 封装一个数据回显
    lookup(id) {
      // console.log(1);
      goodsInfo({ id }).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.goodsForm = res.list;
          // 对图片做一个数据回显
          this.fileList = this.goodsForm.img ? [{ url: this.goodsForm.img }] : [];
          this.goodsForm.id = id;
          // 针对二级分类进行转化
          this.goodsForm.specsattr = this.goodsForm.specsattr.split(",");
          //重新触发change事件目的实现二级联动
          this.changeCate(true);
          this.changeSpecs(true);
          //为了严谨可以把数据重新赋值到富文本编辑器
          this.edit.txt.html(this.goodsForm.description);
        }
      });
    },
    //封装一个创建富文本的事件
    createEdit() {
      //组件一加载就创建富文本
      this.edit = new E("#edit");
      //创建
      this.edit.create();
      //初始化
      this.edit.txt.html(this.goodsForm.description);
      console.log(this.edit, "富文本对象");
    },
    //封装一个清空事件
    reset() {
      this.goodsForm = {
        first_cateid: "", //一级分类编号
        second_cateid: "", //二级分类编号
        goodsname: "", //商品名称
        price: "", //商品价格
        market_price: "", //市场价格
        img: "", //商品图片（文件）
        description: "", //商品描述
        specsid: "", //商品规格编号
        specsattr: "", //商品规格属性
        isnew: 1, //是否新品1是2不是
        ishot: 1, //是否热卖1是2不是
        status: 1, //状态1正常2禁用
      };
      //调用清空验证的方法
      this.$refs.goodsRef.resetFields();
      this.fileList = [];
      //销毁富文本编辑器
      this.edit.destroy();
    },
    // 点击确定
    confirm() {
      this.$refs.goodsRef.validate((val) => {
        if (val) {
          // 对规格属性进行数据格式转化
          // console.log( this.goodsForm.specsattr);
          let aa = this.goodsForm.specsattr.join(",");
          // console.log(aa);
          this.goodsForm.specsattr = aa;
          // console.log(this.goodsForm);
          //获取富文本编辑器的内容
          this.goodsForm.description = this.edit.txt.html();
          if (this.diaInfo.isAdd) {
            console.log(123, goodsAdd);
            goodsAdd(this.goodsForm)
              .then((res) => {
                //   console.log(11);
                //   console.log(res);
                if (res.code == 200) {
                  this.cancel();
                  this.$message.success(res.msg);
                  // 重新调用
                  this.getGoodsListActions();
                  this.getCountActions();
                } else {
                  this.$message.error(res.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            goodsEdit(this.goodsForm).then((res) => {
              //   console.log(11);
              //   console.log(res);
              if (res.code == 200) {
                this.cancel();
                this.$message.success(res.msg);
                // 重新调用
                this.getGoodsListActions();
                this.getCountActions();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
  },
  // 八大生命周期 挂载之后
  mounted() {
    this.getCate();
    this.getspecs();
  },
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters({
      catelist: "cate/getCate",
      specslist: "specs/getSpecsList",
    }),
  },
  filters: {},
  components: {},
};
</script>
<style scoped></style>
